// pages/supermarket/supermarket.js
import {
  getClassifyList,
  getProductPage,
  createOrder,
} from "../../apis/shop_api";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex: -1,
    tabList: [],
    productList: [],
    totalPrice: 0,
    totalNum: 0,
    orderList: [],
    isShowOrder: false
  },
  userData: {
    id: -1,
    page: 0,
    total: 1,
  },
  createOrder() {
    let that = this
    let orderList = this.data.orderList
    let productList = this.data.productList
    let totalPrice = this.data.totalPrice
    let phone = wx.getStorageSync("phoneNumber")
    let points = this.data.points
    if (totalPrice > points) {
      wx.showToast({
        title: "积分不足",
        icon: 'error',
        duration: 2000
      })
      return;
    }
    if (orderList.length > 0) {
      wx.showModal({
        title: '提示',
        content: '确认下单',
        success(res) {
          if (res.confirm) {
            createOrder(phone, orderList, totalPrice).then(res => {
              if (res.success) {
                productList.forEach(product => {
                  product.number = 0
                })
                that.setData({
                  orderList: [],
                  points: res.data.points,
                  totalNum: 0,
                  totalPrice: 0,
                  productList: productList
                })
                // 刷新上一个页面数据并跳转
                let pages = getCurrentPages();
                let releaseList = pages[pages.length - 2];
                releaseList.getPageData()
                wx.navigateBack({
                  delta: 1
                })
                wx.showToast({
                  title: res.message,
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.message,
                  icon: 'error',
                  duration: 2000
                })
              }
            })
          }
        }
      })
    }
  },
  changeIsShowOrder() {
    this.setData({
      isShowOrder: !this.data.isShowOrder
    })
  },
  changePage(e) {
    let page = e.currentTarget.dataset.page
    this.setData({
      pageIndex: page
    })
  },
  changeTabIndex(e) {
    let tabIndex = e.currentTarget.dataset.index
    if (this.data.tabIndex != tabIndex) {
      this.setData({
        tabIndex: tabIndex,
        productList: []
      })
      this.userData.id = tabIndex
      this.userData.page = 0
      this.userData.total = 1
      this.getProductList()
    }
  },
  getProductList() {
    let id = this.userData.id
    let page = this.userData.page + 1
    let total = this.userData.total
    let productList = this.data.productList
    let orderList = this.data.orderList
    if (productList.length < total) {
      getProductPage(id, page, 7).then(res => {
        if (res.success) {
          total = res.data.total ? res.data.total : 1
          let newProductList = res.data.records
          newProductList.forEach(product => {
            orderList.forEach(order => {
              if (product.id == order.id) {
                product.number = order.number
              }
            })
          })
          productList = productList.concat(res.data.records)
          this.setData({
            productList: productList,
          })
          this.userData.total = total
          this.userData.page = page
        } else {
          console.log(res.message);
        }
      })
    }
  },
  add(e) {
    let id = e.currentTarget.dataset.id
    let productList = this.data.productList
    let orderList = this.data.orderList
    let totalPrice = this.data.totalPrice
    let totalNum = this.data.totalNum
    productList.forEach(product => {
      if (product.id == id) {
        if (product.number) {
          product.number = product.number + 1
        } else {
          product.number = 1
        }
        let index = orderList.findIndex(order => order.id == product.id)
        if (index >= 0) {
          orderList[index].number = product.number
        } else {
          let order = {
            "id": product.id,
            "number": product.number,
            "price": product.price,
            "name": product.name
          }
          orderList.push(order)
        }
        totalNum = totalNum + 1
        totalPrice = totalPrice + product.price
      }
    })
    this.setData({
      totalNum: totalNum,
      orderList: orderList,
      totalPrice: totalPrice > 0 ? totalPrice : 0,
      productList: productList
    })
  },
  sub(e) {
    let id = e.currentTarget.dataset.id
    let productList = this.data.productList
    let orderList = this.data.orderList
    let totalPrice = this.data.totalPrice
    let totalNum = this.data.totalNum
    productList.forEach(product => {
      if (product.id == id) {
        if (product.number > 0) {
          product.number = product.number - 1
        } else {
          product.number = 0
        }
        let index = orderList.findIndex(order => order.id == product.id)
        if (index >= 0) {
          if (product.number > 0) {
            orderList[index].number = product.number
          } else {
            orderList.splice(index, 1);
          }
        }
        totalNum = totalNum - 1
        totalPrice = parseFloat(totalPrice) - parseFloat(product.price)
      }
    })
    this.setData({
      totalNum: totalNum,
      orderList: orderList,
      totalPrice: totalPrice > 0 ? totalPrice : 0,
      productList: productList
    })
  },
  getClassifyList() {
    getClassifyList().then(res => {
      if (res.success) {
        let tabList = res.data
        tabList.unshift({
          id: -1,
          name: "全部分类"
        })
        this.setData({
          tabList: tabList,
        })
      } else {
        console.log(res.message);
      }
    })
  },
  clearOrder() {
    let that = this
    let productList = this.data.productList
    let orderList = this.data.orderList
    if (orderList.length > 0) {
      wx.showModal({
        title: '提示',
        content: '确认清空购物车',
        success(res) {
          if (res.confirm) {
            productList.forEach(product => {
              product.number = 0
            })
            that.setData({
              orderList: [],
              totalNum: 0,
              totalPrice: 0,
              productList: productList
            })
          }
        }
      })
    }
  },
  getImg() {
    wx.previewImage({
      current: this.data.store.active, // 当前显示图片的 http 链接
      urls: [this.data.store.active] // 需要预览的图片 http 链接列表
    })
  },
  getPageData() {
    let name = wx.getStorageSync("name")
    let address = wx.getStorageSync("address")
    let avatarUrl = wx.getStorageSync("avatarUrl")
    let points = wx.getStorageSync("points")
    this.setData({
      name, address, avatarUrl, points
    })
    this.getClassifyList()
    this.getProductList()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    wx.getStorage({
      key: 'orderList',
      success(res) {
        let orderList = res.data
        let totalPrice = 0
        let totalNum = 0
        orderList.forEach(order => {
          totalPrice = totalPrice + (order.number * order.price)
          totalNum = totalNum + order.number
        })
        that.setData({
          totalPrice: totalPrice,
          totalNum: totalNum,
          orderList: res.data
        })
        that.getPageData()
      },
      fail() {
        that.setData({
          orderList: []
        })
        that.getPageData()
      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.setStorage({
      key: "orderList",
      data: this.data.orderList
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
